﻿/*-----------------------------------------------------------
 * <copyright file="OrderInfoControl.xaml.cs" company="O-RID">
 *     Copyright (c)2010 O-RID Co.,Ltd.
 * </copyright>
 * <author>Zhang Jun</author>
 * <summary>
 *     *** オーダ情報 数据抽出 查询 ***
 *       
 *          作成日：11/11/2010
 *          
 * </summary>
 *-----------------------------------------------------------
 */
namespace Orid.Management.Statistics.OperatorUnitMangement.ProductionRelated.OrderInfoQuery
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Animation;
    using System.Windows.Shapes;
    using Orid.Management.Statistics.OperatorUnitMangement.Common.SearchCtrl;
    using childWindow = Orid.Management.Statistics.OperatorUnitMangement.Common.Window;
    using Wcf = Orid.Management.Statistics.OperatorUnitMangement.Common.Service;
    using System.Windows.Data;
    using System.Threading;
    using Orid.Management.Statistics.OperatorUnitMangement.WCFServers.OthersQueryRef;
    using Orid.Management.Statistics.OperatorUnitMangement.Common.FunctionList;
    using Orid.Management.Statistics.OperatorUnitMangement.Common.Export;

    /// <summary>
    /// オーダ情報 数据抽出
    /// </summary>
    public partial class OrderInfoControl : UserControl
    {
        #region 全局变量
        /// <summary>
        /// 当前查询框的名字（日志用）
        /// </summary>
        private string ctrlName = " 数据抽出(オーダ情報 ) ";

        /// <summary>
        /// 查询区域对象
        /// DataExtractionContainer
        /// </summary>
        private DataExtractionContainer orderInfoContainer;

        /// <summary>
        /// 日志服务定义
        /// WCFLog4Client
        /// </summary>
        private WCFLog4Ref.WCFLog4Client wcfLogClient;

        /// <summary>
        /// 消息子窗体
        /// errorMessbox
        /// </summary>
        private childWindow.MessageBox errorMessbox;

        /// <summary>
        /// 分页控件
        /// PagedCollectionView
        /// </summary>
        private PagedCollectionView pcv;

        /// <summary>
        /// 存放导出数据
        /// </summary>
        private DataGrid dataToCSV = null;

        /// <summary>
        /// 记录总数（排序后导出用）
        /// </summary>
        private int sumRecordCount = 0;

        /// <summary>
        /// 记录NumericUpDown分页数
        /// </summary>
        private double oldNumericUpDown = 0;

        #endregion 全局变量


        /// <summary>
        /// オーダ情報 数据抽出 构造函数
        /// </summary>
        public OrderInfoControl(DataExtractionContainer orderInfoContainers)
        {
            InitializeComponent();

            this.InitField();

            // 引用主题
            ((App)Application.Current).SetTheme((Grid)LayoutRoot);

            this.dgOrderInfoList.HeadersVisibility = DataGridHeadersVisibility.All;//同时显示DataGrid的行头与列头

            this.orderInfoContainer = orderInfoContainers;

            #region 设置查询
            Command.Other.OrderInfoQuery queryCommand = new Command.Other.OrderInfoQuery(orderInfoContainers);

            queryCommand.ExecOver -= new EventHandler<OrderInfoCompletedEventArgs>(QueryCommand_ExecOver);
            queryCommand.ExecBegin -= new EventHandler<EventArgs>(QueryCommand_ExecBegin);

            queryCommand.ExecOver += new EventHandler<OrderInfoCompletedEventArgs>(QueryCommand_ExecOver);
            queryCommand.ExecBegin += new EventHandler<EventArgs>(QueryCommand_ExecBegin);

            this.orderInfoContainer.QueryCcommand = queryCommand;
            #endregion 设置查询

            #region 设置导出
            //导出
            Command.DateExport exportCommand = new Command.DateExport();
            //导出开始
            exportCommand.ExecBegin += new EventHandler<EventArgs>(this.ExportCommand_ExecBegin);

            this.orderInfoContainer.ExportComand = exportCommand;
            #endregion 设置导出

            //控件上的导出按钮
            this.orderInfoContainer.btnExport.IsEnabled = true;
            //控件上的order状态不显示
            this.orderInfoContainer.cbOverMark.Visibility = Visibility.Collapsed;
            this.orderInfoContainer.tbOverMark.Visibility = Visibility.Collapsed;

            //设置 查询界面 的 查询按钮 初始化可用
            this.orderInfoContainer.btnSearch.IsEnabled = true;

            this.nuPageSize.IsEnabled = true; //分页数量 

            // 设置背景色
            LayoutRoot.Background = new SolidColorBrush(Color.FromArgb(255, 243, 244, 245));

        }


        /// <summary>
        /// 初始化变量 InitField
        /// </summary>  
        private void InitField()
        {
            this.errorMessbox = new childWindow.MessageBox();
            this.wcfLogClient = Wcf.Service.Log4;
            dataToCSV = new DataGrid();
        }

        #region BusyBar
        /// <summary>
        /// 让BusyBar开始
        /// SetBusyBar
        /// </summary>
        /// <param name="busySeconds">busy秒数 busysecond</param>
        public void SetBusyBar(int busySeconds)
        {
            int delayMilliseconds = 2;
            biBusyBar.DisplayAfter = TimeSpan.FromMilliseconds(delayMilliseconds);

            DataContext = true;

            this.nuPageSize.IsEnabled = false; //分页数量 09/28/2010 Add
            ThreadPool.QueueUserWorkItem((state) =>
            {
                Thread.Sleep(busySeconds * 1000);
            });
        }

        #endregion BusyBar

        /// <summary>
        /// 查询开始
        /// QueryCommand_ExecBegin
        /// </summary>
        /// <param name="sender">sender of object</param>
        /// <param name="e">e type of EventArgs</param>
        private void QueryCommand_ExecBegin(object sender, EventArgs e)
        {
            this.SetBusyBar(100);
        }

        /// <summary>
        /// 查询开始
        /// OP别期间别查询
        /// </summary>
        /// <param name="sender">sender of object</param>
        /// <param name="e">e type of OrderInfoCompletedEventArgs</param>
        private void QueryCommand_ExecOver(object sender, OrderInfoCompletedEventArgs e)
        {
            try
            {
                //设置 查询界面 的 查询按钮 初始化可用
                this.orderInfoContainer.btnSearch.IsEnabled = true;

                if (e.Error == null)
                {
                    if (e.Result.Count > 0)
                    {
                        //记录所查询的记录总数（导出结果与排序内容一致用）
                        this.sumRecordCount = e.Result.Count;

                        this.pcv = new PagedCollectionView(e.Result);
                        this.pcv.PageSize = Convert.ToInt32(this.nuPageSize.Value);

                        this.dgOrderInfoList.ItemsSource = this.pcv;
                        this.dpDataPage.DataContext = this.pcv;

                        this.dataToCSV.ItemsSource = null;
                        this.dataToCSV.ItemsSource = e.Result;

                        Dispatcher.BeginInvoke(() => DataContext = false);
                        this.nuPageSize.IsEnabled = true; //分页数量 

                        this.wcfLogClient.InfoAsync(((App)Application.Current).LogStr +
                                                    "在" + this.ctrlName + "中 查询中查询记录" +
                                                    orderInfoContainer.WhereIntorLogs);
                    }
                    else
                    {
                        this.dgOrderInfoList.ItemsSource = null;
                        this.dpDataPage.DataContext = null;
                        this.dataToCSV.ItemsSource = null;


                        throw new Exception(this.ctrlName + " 查询没有可显示的数据");
                    }
                }
                else
                {
                    throw new Exception("OrderInforCompleted 服务返回值有错" + e.Error.Message.ToString());
                }
            }
            catch (Exception exce)
            {
                string exceptionStr = FunctionClass.GetMessageInformation(exce);

                Dispatcher.BeginInvoke(() => DataContext = false);
                this.nuPageSize.IsEnabled = true; //分页数量 09/28/2010 Add

                this.wcfLogClient.ErrorAsync(((App)Application.Current).LogStr +
                                                        ctrlName +
                                                        exceptionStr +
                                                        orderInfoContainer.WhereIntorLogs);
                FunctionClass.ShowMessageBox(
                   this.errorMessbox,
                   1,
                   "提示",
                   exceptionStr,
                   Colors.Gray,
                   true,
                   Visibility.Visible,
                   Visibility.Collapsed);
                return;
            }
        }

        #region 数据导出  08/10/2010 -- ADD

        /// <summary>
        /// 导出开始
        /// ExportCommand_ExecBegin
        /// </summary>
        /// <param name="sender">sender of object</param>
        /// <param name="e">e type of EventArgs</param>
        private void ExportCommand_ExecBegin(object sender, EventArgs e)
        {
            this.ExportDate();
        }

        /// <summary>
        /// 导出 按钮  
        /// ExportDate
        /// </summary>        
        private void ExportDate()
        {
            try
            {
                //设置 查询界面 的 数据导出 可用
                this.orderInfoContainer.btnExport.IsEnabled = true;

                if (this.dgOrderInfoList.ItemsSource == null)
                {
                    throw new Exception("请查询后再将数据导出。");
                }
                else
                {
                    //导出结果与排序内容一致用
                    this.oldNumericUpDown = this.nuPageSize.Value;
                    this.pcv.PageSize = this.sumRecordCount;
                    this.dataToCSV.ItemsSource = this.pcv;

                    this.ExportDataToFile(this.dgOrderInfoList);
                }
            }
            catch (Exception ex)
            {

                this.wcfLogClient.ErrorAsync(((App)Application.Current).LogStr +
                                                    " ExportDate(" + this.ctrlName + "DataExtractionControl ) " +
                                                    ex.Message.ToString() +
                                                    orderInfoContainer.WhereIntorLogs);
                FunctionClass.ShowMessageBox(
                    this.errorMessbox,
                    1,
                    "提示",
                   ex.Message.ToString(),
                   Colors.Gray,
                   true,
                   Visibility.Visible,
                   Visibility.Collapsed);
                return;
            }
        }

        /// <summary>
        /// 数据导出
        /// ExportDataToFile
        /// </summary>
        /// <param name="grid">带有显示格式的 grid</param>
        /// <value>10/14/2010 修改 导出功能异常</value>
        private void ExportDataToFile(DataGrid grid)
        {
            try
            {
                SaveFileDialog sfd = new SaveFileDialog();
                sfd.DefaultExt = "csv";
                sfd.Filter = "CSV Files (*.csv)|*.csv|All files (*.*)|*.*";

                sfd.FilterIndex = 1;
                bool? ret = sfd.ShowDialog();
                if (ret == true)
                {
                    string data = DataExport.ExportDataGrid(true, grid, this.dataToCSV, null);

                    using (System.IO.Stream stream = sfd.OpenFile())
                    {
                        using (System.IO.StreamWriter writer = new System.IO.StreamWriter(stream, System.Text.UnicodeEncoding.Unicode))
                        {
                            //由 逗号 换成 ^ ,--07/30/2010--EIDT 修改 千分位分割符用TAB替换问题
                            data = data.Replace("^", "\t");
                            writer.Write(data);
                            writer.Close();
                        }

                        stream.Close();
                    }

                    this.pcv.PageSize = Convert.ToInt32(this.oldNumericUpDown);

                    this.wcfLogClient.InfoAsync(((App)Application.Current).LogStr +
                                                        "在 " + this.ctrlName + " 查询中导出记录" +
                                                        orderInfoContainer.WhereIntorLogs);

                    FunctionClass.ShowMessageBox(
                      this.errorMessbox,
                      0,
                     "提示",
                     "数据已导出。",
                     Colors.Gray,
                     true,
                     Visibility.Visible,
                     Visibility.Collapsed);
                    return;
                }
                else
                {
                    this.pcv.PageSize = Convert.ToInt32(this.oldNumericUpDown);
                    return;
                }
            }
            catch (Exception ex)
            {
                this.pcv.PageSize = Convert.ToInt32(this.oldNumericUpDown);
                this.wcfLogClient.ErrorAsync(((App)Application.Current).LogStr +
                                                " ExportDataToFile(" + this.ctrlName + ") " +
                                                ex.Message.ToString() +
                                                orderInfoContainer.WhereIntorLogs);

                FunctionClass.ShowMessageBox(
                    this.errorMessbox,
                    1,
                   "提示",
                   ex.Message.ToString(),
                   Colors.Gray,
                   true,
                   Visibility.Visible,
                   Visibility.Collapsed);
                return;
            }
        }

        #endregion 数据导出




    }
}
